package com.apes.framework.plugin.esb.processor.router;

import com.apes.framework.api.SpringManager;
import com.apes.framework.plugin.esb.api.Request;
import com.apes.framework.plugin.esb.processor.AbstractChainProcessor;
import com.apes.framework.util.CacheUtil;
import com.apes.framework.util.PropertiesUtils;
import com.apes.framework.util.Tools;
import org.springframework.util.StringUtils;

import java.util.Map;

/**
 * 功能：Filter处理器类
 *
 * @author xul
 * @create 2017-12-05 8:55
 */
public class FilterProcessor<T extends Request, R> extends AbstractChainProcessor<T, R> {
    private String condition;
    private String defaultCondition;

    public String getCondition() {
        return condition;
    }

    public void setCondition(String condition) {
        this.condition = condition;
    }

    public String getDefaultCondition() {
        return defaultCondition;
    }

    public void setDefaultCondition(String defaultCondition) {
        this.defaultCondition = defaultCondition;
    }

    public boolean execute(Map row) {
        Object o;
        try {
            condition = Tools.replace(condition);
        } catch (Exception e) {
            if (StringUtils.hasText(defaultCondition)) {
                condition = defaultCondition;
            } else {
                throw new RuntimeException(e);
            }
        }
        try {
            o = CacheUtil.getEngine().execute(condition, row); //条件表达式
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(String.format("表达式：%s执行错误，上下文件环境：%s", condition, row.toString()));
        }
        if (!(o instanceof Boolean)) {
            throw new RuntimeException(String.format("表达式：%s" + " 定义错误！", condition));
        }
        if (o.equals(true)) {
            return true;
        }
        return false;
    }

    @Override
    protected R doProcess(T data) {
        return null;
    }

}
